package it.isa.demo.service;

import it.isa.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Corgile
 * @date 2022-02-26
 */
@Service
public class UserService {
	@Autowired
	@Qualifier(value = "jdbcTemplateOne")
	private JdbcTemplate templateOne;

	@Autowired
	@Qualifier(value = "jdbcTemplateTwo")
	private JdbcTemplate templateTwo;

	// plaint string
	public String getUserById(Integer id) {
		System.out.println("getUserNameById");
		return "user";
	}

	public void deleteUserNameById(Integer id) {
		System.out.println("deleteUserNameById");
	}

	// live data by jdbc
	public Integer jdbcAddUser(User user) {
		return this.templateOne.update("INSERT INTO user (name, age, address) VALUES(?, ?, ?);",
				user.getName(), user.getAge(), user.getAddress());
	}

	public Integer jdbcUpdateNameById(User user) {
		return this.templateOne.update("UPDATE user SET name = ? WHERE id = ?;",
				user.getName(), user.getUserId());
	}

	public Integer jdbcDeleteUserById(Integer id) {
		return this.templateOne.update("DELETE FROM user WHERE id = ?", id);
	}

	public List<User> jdbcGetAllUsersFromDsOne() {
		return this.templateOne.query("SELECT * FROM user", (resultSet, rowNum) -> {
			User user = new User();
			int id = resultSet.getInt("id");
			int age = resultSet.getInt("age");
			String name = resultSet.getString("name");
			String address = resultSet.getString("address");
			user.setUserId(id);
			user.setName(name);
			user.setAge(age);
			user.setAddress(address);
			return user;
		});
	}

	public List<User> jdbcGetAllUsersFromDsTwo() {
		return this.templateTwo.query("SELECT * FROM user", (set, row) -> {
			User user = new User();
			int id = set.getInt("id");
			int age = set.getInt("age");
			String name = set.getString("name");
			String address = set.getString("address");
			user.setUserId(id);
			user.setName(name);
			user.setAge(age);
			user.setAddress(address);
			return user;
		});
	}

}
